package demo.java.util;


import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangly on @date 2023/5/16
 */
public class CSVSplitter {
    public static void main(String[] args) {
        String csvFile = "D:\\work\\智能审核\\20230530\\郑大一2022年全年违规明细_过滤.csv";  // 输入的CSV文件路径
        String splitColumn = "执行科室名称";  // 拆分的列名
        String outputDirectory = "D:\\work\\智能审核\\20230530\\output\\";  // 输出文件的目录

        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(new FileInputStream(csvFile),"GBK");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try (BufferedReader br = new BufferedReader(isr)) {
            String line;
            boolean headerLine = true;
            int splitColumnIndex = 0;
            Map<String, FileWriter> fileWriters = new HashMap<>();

            while ((line = br.readLine()) != null) {
                if (headerLine) {
                    String[] headers = line.split(",");
                    for (int i = 0; i < headers.length; i++) {
                        if (headers[i].equalsIgnoreCase(splitColumn)) {
                            splitColumnIndex = i;
                            break;
                        }
                    }
                    headerLine = false;
                    continue;
                }

                String[] data = line.split(",");
                String splitColumnValue = data[splitColumnIndex].trim();

                FileWriter fileWriter = fileWriters.get(splitColumnValue);

                splitColumnValue = splitColumnValue.replace("/","-");
                if (fileWriter == null) {
                    String outputFilePath = outputDirectory + splitColumnValue + ".csv";
                    fileWriter = new FileWriter(outputFilePath);
                    fileWriters.put(splitColumnValue, fileWriter);
                }

                fileWriter.write(line + "\n");
            }

            // 关闭所有的文件写入器
            for (FileWriter fw : fileWriters.values()) {
                fw.close();
            }

            System.out.println("拆分完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

